package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 用户登录功能
 *
 * 首先:
 * 要求用户输入用户名和密码
 * 然后链接数据库，使用用户输入的用户名和密码作为过滤条件去userinfo表中查询该用户信息
 * 如果可以查询到记录则表示登录成功，否则登录失败
 *
 * SQL:
 * SELECT id,username,password,nickname,age
 * FROM userinfo
 * WHERE username='用户输入的用户名' AND password='用户输入的密码'
 *
 * a' OR '1'='1
 */
public class LoginUserDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("用户登录");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();

        try (Connection connection = DBUtil.getConnection();){
            Statement statement = connection.createStatement();
            String sql = "SELECT username,password,nickname,age " +
                         "FROM userinfo " +
                         "WHERE username='"+username+"' AND password='"+password+"'";
            ResultSet rs = statement.executeQuery(sql);
            if(rs.next()){
                String nickname = rs.getString("nickname");
                System.out.println("登录成功,欢迎["+nickname+"]回来");
            }else{
                System.out.println("登录失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
